﻿using CommandLine;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NK.Tools.Options
{
    [Verb("clean-dll", HelpText = "Generate guid")]
    public class CleanDll : OptionHandlerBase
    {
        [Option('p', "RootPath", Required = false, HelpText = "Will clean the temp directory of Visual Studio, like obj and bin")]
        public string RootDirectory { get; set; }

        private List<string> AllDirectories { get; set; } = new List<string>();

        private List<string> DirectoriesToBeDeleted { get; set; } = new List<string>();

        private List<string> FilesToBeDeleted { get; set; } = new List<string>();

        public override void HandleOption()
        {
            if (string.IsNullOrEmpty(RootDirectory))
            {
                RootDirectory = Environment.CurrentDirectory;
            }

            Console.WriteLine($"root path: {RootDirectory}");

            SetAllDirectories(RootDirectory);

            SetToBeDeletedDirectories();

            SetToBeDeletedFiles();

            foreach (var item in FilesToBeDeleted)
            {
                Console.WriteLine($"Files: {item}");
                if (File.Exists(item))
                {
                    File.Delete(item);
                }
            }

            DirectoriesToBeDeleted = DirectoriesToBeDeleted.OrderByDescending(c => c.Length).ToList();
            foreach (var item in DirectoriesToBeDeleted)
            {
                Console.WriteLine($"Directory: {item}");
                if (Directory.Exists(item))
                {
                    Directory.Delete(item);
                }
            }

        }

        private void SetToBeDeletedDirectories()
        {
            foreach (var item in AllDirectories)
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(item);
                if (directoryInfo.FullName.Contains("\\obj\\") || directoryInfo.FullName.EndsWith("\\obj") || directoryInfo.FullName.Contains("\\Debug"))
                {
                    DirectoriesToBeDeleted.Add(item);
                }
            }
        }

        private void SetToBeDeletedFiles()
        {
            foreach (var directory in DirectoriesToBeDeleted)
            {
                var files = Directory.GetFiles(directory);
                FilesToBeDeleted.AddRange(files);
            }
        }

        private void SetAllDirectories(string directoryPath)
        {
            var allSubDirectories = Directory.GetDirectories(directoryPath);
            AllDirectories.AddRange(allSubDirectories);
            if (allSubDirectories.Count() > 0)
            {
                foreach (var item in allSubDirectories)
                {
                    SetAllDirectories(item);
                }
            }
        }
    }
}
